using Microsoft.EntityFrameworkCore;
using net_work.Config;
using net_work.Data.DTO.Hmw;
using net_work.Data.Entity.Hmw;
using net_work.Data.Enum.Hmw;
using net_work.IRepository.Hmw;

namespace net_work.Repository.Hmw;

public class QuestionAnswerSubmissionRepository(ApplicationDbContext dbContext)
    : Repository<QuestionAnswerSubmission>(dbContext), IQuestionAnswerSubmissionRepository
{
    public async Task<long> UpdateAsync(
        QuestionAnswerSubmissionUpdateRequestBackend questionAnswerSubmissionUpdateRequestBackend)
    {
        var questionAnswerSubmission =
            await dbContext.QuestionAnswerSubmissions.FirstOrDefaultAsync(x =>
                x.HomeworkQuestionId == questionAnswerSubmissionUpdateRequestBackend.HomeworkQuestionId &&
                x.StudentId == questionAnswerSubmissionUpdateRequestBackend.StudentId);
        if (questionAnswerSubmission == null)
        {
            await dbContext.QuestionAnswerSubmissions.AddAsync(new QuestionAnswerSubmission
            {
                Content = questionAnswerSubmissionUpdateRequestBackend.Content,
                Status = SubmissionStatus.No,
                HomeworkQuestionId = questionAnswerSubmissionUpdateRequestBackend.HomeworkQuestionId,
                StudentId = questionAnswerSubmissionUpdateRequestBackend.StudentId,
                Remark = questionAnswerSubmissionUpdateRequestBackend.Remark
            });
            await dbContext.SaveChangesAsync();

            if (questionAnswerSubmission != null)
            {
                return questionAnswerSubmission.Id;
            }

            return -1;
        }

        questionAnswerSubmission.Content = questionAnswerSubmissionUpdateRequestBackend.Content;
        questionAnswerSubmission.Remark = questionAnswerSubmissionUpdateRequestBackend.Remark;

        await dbContext.SaveChangesAsync();
        return questionAnswerSubmission.Id;
    }

    public async Task<bool> SubmitAsync(
        QuestionAnswerSubmissionUpdateRequestBackend questionAnswerSubmissionUpdateRequestBackend)
    {
        var questionAnswerSubmission =
            await dbContext.QuestionAnswerSubmissions.FindAsync(questionAnswerSubmissionUpdateRequestBackend.Id);
        if (questionAnswerSubmission == null)
        {
            return false;
        }

        questionAnswerSubmission.Remark = questionAnswerSubmissionUpdateRequestBackend.Remark;
        questionAnswerSubmission.Content = questionAnswerSubmissionUpdateRequestBackend.Content;
        questionAnswerSubmission.Score = questionAnswerSubmissionUpdateRequestBackend.Score;
        questionAnswerSubmission.Status = SubmissionStatus.Yes;
        questionAnswerSubmission.FirstSubmissionTime ??= DateTime.Now.ToLocalTime();
        questionAnswerSubmission.LastSubmissionTime = DateTime.Now.ToLocalTime();

        return await dbContext.SaveChangesAsync() > 0;
    }
}